package level;

import goliath.BasicDemo;
import pulpfizz.physics.NewWorld;
import org.jbox2d.dynamics.Body;

/**
 * Level type that requires the user to build a tower of the specified height.
 *
 * @author will
 * @date Aug 10, 2008 12:46:13 PM
 */
public class StackHeightLevel extends AbstractLevel {
    StackHeightLine heightLine;

    public StackHeightLevel() {
        BasicDemo.getPhysics().add(new StackHeightSprite(targetHeight));
        heightLine = new StackHeightLine();
        BasicDemo.getPhysics().add(heightLine);
    }
    public float targetHeight = 5f;

    public String getTitle() {
        return "Stack 'em high!";
    }

    public boolean isLevelWon() {
        return levelWon;
    }

    boolean levelWon = false;

    int totalElapsed = 0;
    public void update(int elapsedTime) {
        totalElapsed+= elapsedTime;
        if(totalElapsed < 200) return;
        totalElapsed = 0;

        NewWorld w = BasicDemo.getWorld();
        Body body = w.getBodyList();
        boolean moving = false;
        boolean stackHeight = false;
        float stack = Float.NEGATIVE_INFINITY;
        float vel = Float.MIN_VALUE;
        while (body != null) {
            if (body.hashCode() != BasicDemo.border.hashCode() &&
                    body.m_mass>0) {

                if (body.getLinearVelocity().length() > 0.1f) {
                    moving = true;
                }
                if (body.getWorldCenter().y > targetHeight) {
                    stackHeight = true;
                }
                stack = Math.max(stack, body.getWorldCenter().y);
                vel = Math.min(vel, body.getLinearVelocity().length());
            }
            body = body.m_next;
        }
        heightLine.point.set(stack);
        moving = moving || BasicDemo.isGrabbing();
        heightLine.moving = moving;
        if (!moving && stackHeight) {
            System.out.println("Won the level!");
            levelWon = true;
        }
    }
}
